"use client";

import { Menu, Plus } from "lucide-react";
import * as React from "react";
import { nanoid } from "nanoid";
import Link from "next/link";
import { useRouter } from "next/navigation";

import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarHeader,
  SidebarMenuButton,
  SidebarRail,
  SidebarTrigger,
  useSidebar,
} from "~/components/ui/sidebar";
import { useEffect, useState } from "react";
import { createClient } from "~/lib/supabase/client";
import { VoraLogo } from "~/components/vora/vora-logo";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "~/components/ui/tooltip";
import { useIsMobile } from "~/hooks/use-mobile";
import { cn } from "~/lib/utils";
import { NavUser } from "./nav-user";
import { useAgentCode } from "~/hooks/use-agent-code";
import { NavAgents } from "./nav-agents";

export function SidebarLeft({
  ...props
}: React.ComponentProps<typeof Sidebar>) {
  const { state, setOpen, setOpenMobile } = useSidebar();
  const isMobile = useIsMobile();
  const [user, setUser] = useState<{
    name: string;
    email: string;
    avatar: string;
  }>({
    name: "加载中...",
    email: "loading@example.com",
    avatar: "",
  });

  const agentCode = useAgentCode();
  const router = useRouter();

  useEffect(() => {
    const fetchUserData = async () => {
      const supabase = createClient();
      const { data } = await supabase.auth.getUser();

      if (data.user) {
        setUser({
          name:
            data.user.user_metadata?.name ||
            data.user.email?.split("@")[0] ||
            "用户",
          email: data.user.email || "",
          avatar: data.user.user_metadata?.avatar_url || "",
        });
      }
    };

    fetchUserData();
  }, []);

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key === "b") {
        event.preventDefault();
        setOpen(!state.startsWith("expanded"));
        window.dispatchEvent(
          new CustomEvent("sidebar-left-toggled", {
            detail: { expanded: !state.startsWith("expanded") },
          }),
        );
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [state, setOpen]);

  const newTask = React.useCallback(() => {
      router.push(`/agents/${agentCode}?threadId=${nanoid()}`);
  }, [agentCode, router]);

  return (
    <Sidebar
      collapsible="icon"
      className="bg-background/95 border-r-0 backdrop-blur-sm [-ms-overflow-style:'none'] [scrollbar-width:'none'] [&::-webkit-scrollbar]:hidden"
      {...props}
    >
      <SidebarHeader className="px-2 py-2">
        <div className="relative flex h-[40px] items-center px-1">
          <Link href="/">
            <VoraLogo showVora={state === "expanded"} />
          </Link>
          {state !== "collapsed" && (
            <div className="ml-2 whitespace-nowrap transition-all duration-200 ease-in-out"></div>
          )}
          <div className="ml-auto flex items-center gap-2">
            {state !== "collapsed" && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <SidebarTrigger className="h-8 w-8" />
                </TooltipTrigger>
                <TooltipContent>切换侧边栏 (CMD+B)</TooltipContent>
              </Tooltip>
            )}
            {isMobile && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    onClick={() => setOpenMobile(true)}
                    className="hover:bg-accent flex h-8 w-8 items-center justify-center rounded-md"
                  >
                    <Menu className="h-4 w-4" />
                  </button>
                </TooltipTrigger>
                <TooltipContent>打开菜单</TooltipContent>
              </Tooltip>
            )}
          </div>
        </div>
      </SidebarHeader>
      <SidebarContent className="[-ms-overflow-style:'none'] [scrollbar-width:'none'] [&::-webkit-scrollbar]:hidden">
        <SidebarGroup>
          <SidebarMenuButton
            className={cn({
              "bg-accent text-accent-foreground font-medium": !!agentCode,
            })}
            onClick={newTask}
          >
            <Plus className="mr-1 h-4 w-4" />
            <span className="flex w-full items-center justify-between">
              新建任务
            </span>
          </SidebarMenuButton>
        </SidebarGroup>
        <NavAgents />
      </SidebarContent>
      <SidebarFooter>
        {state === "collapsed" && (
          <div className="mt-2 flex justify-center">
            <Tooltip>
              <TooltipTrigger asChild>
                <SidebarTrigger className="h-8 w-8" />
              </TooltipTrigger>
              <TooltipContent>展开侧边栏 (CMD+B)</TooltipContent>
            </Tooltip>
          </div>
        )}
        <NavUser user={user} />
      </SidebarFooter>
      <SidebarRail />
    </Sidebar>
  );
}
